<template>
  <el-dropdown trigger="click">
    <div class="flex-center user-wrap">
      <img :src="userStore.userInfo.avatar || defaultAvatar" class="avatar" />
      <span>{{ userStore.userInfo.username || '游客，您好！' }}</span>
    </div>
    <template #dropdown>
      <el-dropdown-menu>
        <el-dropdown-item @click="handleOpenUserProfile">
          个人中心
        </el-dropdown-item>
        <el-dropdown-item divided @click="logout">
          退出登录
        </el-dropdown-item>
      </el-dropdown-menu>
    </template>
  </el-dropdown>
</template>

<script setup>
defineOptions({
  name: "UserProfile"
});

import { useTagsViewStore, useUserStore } from "@/store"
import defaultAvatar from "@/assets/images/avatar.png"
import { ref } from "vue";

const tagsViewStore = useTagsViewStore()
const userStore = useUserStore()

const route = useRoute()
const router = useRouter()

const nickname = ref('')
const onMounted = () => {
  const { name } = JSON.parse(sessionStorage.getItem("userInfo"))
  nickname.value = name
}
/**
 * 打开个人中心页面
 */
function handleOpenUserProfile() {
  router.push({ name: "Profile" })
}

/**
 * 注销登出
 */
function logout() {
  ElMessageBox.confirm('确定注销并退出系统吗？', '提示', {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
    lockScroll: false,
  }).then(() => {
    userStore
      .logout()
      .then(() => {
        tagsViewStore.delAllViews()
      })
      .then(() => {
        router.push(`/login?redirect=${route.fullPath}`)
      })
  })
}
</script>

<style lang="scss" scoped>
.user-wrap {
  // height: 100%;
  padding-right: 15px;
  .avatar {
    width: 50px;
    height: 50px;
    margin-right: 10px;
    border-radius: 50%;
    overflow: hidden;
  }
}
</style>
